package cn.xiuxius.askbox.service.impl;

import cn.xiuxius.askbox.common.utils.MailUtil;
import cn.xiuxius.askbox.mapper.AnswerMapper;
import cn.xiuxius.askbox.mapper.AskMapper;
import cn.xiuxius.askbox.mapper.UserMapper;
import cn.xiuxius.askbox.pojo.dto.add.AskAddDTO;
import cn.xiuxius.askbox.pojo.dto.update.AskUpdateStateDTO;
import cn.xiuxius.askbox.pojo.dto.query.AskQueryDTO;
import cn.xiuxius.askbox.pojo.dto.update.AskUpdateDTO;
import cn.xiuxius.askbox.pojo.entity.AnswerEntity;
import cn.xiuxius.askbox.pojo.entity.AskEntity;
import cn.xiuxius.askbox.pojo.entity.UserEntity;
import cn.xiuxius.askbox.pojo.result.PageResult;
import cn.xiuxius.askbox.pojo.vo.AskVO;
import cn.xiuxius.askbox.service.IAskService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xiaoxiu
 * @since 2024-07-20
 */
@Service
public class AskServiceImpl extends ServiceImpl<AskMapper, AskEntity> implements IAskService {

    @Autowired
    private AskMapper askMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MailUtil mailUtil;

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private AnswerMapper answerMapper;

    @Override
    public PageResult getAsksByPage(AskQueryDTO dto) {
        //查询条件
        LambdaQueryWrapper<AskEntity> wrapper = Wrappers.<AskEntity>lambdaQuery()
                .like(StringUtils.isNotBlank(dto.getUuid()), AskEntity::getUuid, dto.getUuid())
                .like(StringUtils.isNotBlank(dto.getUserUuid()), AskEntity::getUserUuid, dto.getUserUuid())
                .like(StringUtils.isNotBlank(dto.getAgent()), AskEntity::getAgent, dto.getAgent())
                .eq(Objects.nonNull(dto.getAnswerState()), AskEntity::getAnswerState, dto.getAnswerState())
                .like(StringUtils.isNotBlank(dto.getIp()), AskEntity::getIp, dto.getIp())
                .like(StringUtils.isNotBlank(dto.getReplyEmail()), AskEntity::getReplyEmail, dto.getReplyEmail())
                .eq(AskEntity::getState, dto.getState())
                .like(StringUtils.isNotBlank(dto.getContent()), AskEntity::getContent, dto.getContent())
                .between(Objects.nonNull(dto.getCreateTimeBegin()) && Objects.nonNull(dto.getCreateTimeEnd()), AskEntity::getCreateTime, dto.getCreateTimeBegin(), dto.getCreateTimeEnd())
                .orderByDesc(AskEntity::getCreateTime);

        Page<AskEntity> pageResult = askMapper.selectPage(new Page<>(dto.getPage(), dto.getPageSize()), wrapper);

        List<AskVO> vos = new LinkedList<>();

        for (AskEntity record : pageResult.getRecords()) {
            AskVO vo = new AskVO();
            BeanUtils.copyProperties(record, vo);
            vos.add(vo);
        }

        return new PageResult(pageResult.getTotal(), vos);
    }

    @Override
    public AskVO getAskByAskUuid(AskQueryDTO dto) {

        AskEntity askEntity = askMapper.selectOne(Wrappers.<AskEntity>lambdaQuery()
                .eq(AskEntity::getUuid, dto.getUuid())
                .eq(AskEntity::getState, dto.getState())
        );

        AskVO vo = new AskVO();
        BeanUtils.copyProperties(askEntity, vo);
        return vo;
    }

    @Override
    public void updateAskByAskUuid(AskUpdateDTO dto) {
        askMapper.update(null, Wrappers.<AskEntity>lambdaUpdate()
                .eq(AskEntity::getUuid, dto.getUuid())
                .set(StringUtils.isNotBlank(dto.getContent()), AskEntity::getContent, dto.getContent())
                .set(StringUtils.isNotBlank(dto.getReplyEmail()), AskEntity::getReplyEmail, dto.getReplyEmail())
        );
    }

    @Override
    public void deleteAskByAskUuid(String uuid) {
        askMapper.delete(Wrappers.<AskEntity>lambdaQuery().eq(AskEntity::getUuid, uuid));
        //关联的回答也要删除
        answerMapper.delete(Wrappers.<AnswerEntity>lambdaQuery().eq(AnswerEntity::getAskUuid, uuid));
    }

    @Override
    public void updateStateAskByAskUuid(AskUpdateStateDTO dto) {
        askMapper.update(null, Wrappers.<AskEntity>lambdaUpdate()
                .eq(AskEntity::getUuid, dto.getUuid())
                .set(Objects.nonNull(dto.getState()), AskEntity::getState, dto.getState())
        );
    }

    @Override
    public void submitAsk(AskAddDTO dto) {
        AskEntity askEntity = new AskEntity();
        BeanUtils.copyProperties(dto, askEntity);
        askEntity.setIp(request.getRemoteAddr());
        askEntity.setAgent(request.getHeader("User-Agent"));
        askEntity.setUuid(UUID.randomUUID().toString());
        askMapper.insert(askEntity);

        //通知用户
        UserEntity userEntity = userMapper.selectOne(Wrappers.<UserEntity>lambdaQuery()
                .eq(UserEntity::getUuid, dto.getUserUuid())
        );

        StringBuilder content = new StringBuilder();

        content.append("<div>")
                .append("<p>您好，您有新的提问：</p>")
                .append("<p>问题内容：").append(dto.getContent()).append("</p>")
                .append("</div>");
        mailUtil.sendMail(userEntity.getEmail(), "提问通知", content.toString());

    }
}
